package com.lechi.web.util;

import com.lechi.web.framework.log.IotExceptionLog;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.CompletableFuture;

/**
 * The type Port checker.
 */
@Slf4j
public class PortChecker {
    /**
     * Is port in use boolean.
     *
     * @param port the port
     * @return the boolean
     */
    public static boolean isPortInUse(int port) {

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            return false;
        } catch (IOException e) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            String method = Thread.currentThread().getName() + ":" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
            CompletableFuture.runAsync(IotExceptionLog.exceptionLog(e, "端口已经被占用", method, port));
            log.error("开启Socket服务时端口：{} 已经被占用", port);
            return true;
        }
    }

}